"use client"

import { useState } from "react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Checkbox } from "@/components/ui/checkbox"
import { Droplets, ArrowRight } from "lucide-react"
import { apiService } from "@/lib/services/api"

export default function LoginPage() {
  const router = useRouter()
  const [email, setEmail] = useState("")
  const [password, setPassword] = useState("")
  const [rememberMe, setRememberMe] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const handleLogin = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    setError(null)
    setIsLoading(true)

    try {
      console.log('尝试登录...')
      const response = await apiService.auth.login({ email, password })
      
      console.log('登录响应:', {
        status: response.status,
        error: response.error,
        hasData: !!response.data
      })

      if (response.error) {
        setError(response.error)
        return
      }

      // 登录成功，跳转到仪表板
      console.log('登录成功，准备跳转...')
      router.push("/dashboard")
    } catch (error: unknown) {
      console.error('登录过程中发生错误:', error)
      const errorMessage = error instanceof Error ? error.message : '未知错误'
      setError(`登录失败: ${errorMessage}`)
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="min-h-screen flex flex-col items-center justify-center bg-gradient-to-b from-green-50 to-blue-50 p-4">
      <div className="w-full max-w-md">
        <div className="flex justify-center mb-6">
          <div className="flex items-center gap-2">
            <Droplets className="h-10 w-10 text-green-600" />
            <h1 className="text-3xl font-bold text-green-800">智能灌溉系统</h1>
          </div>
        </div>

        <Card>
          <CardHeader>
            <CardTitle>登录</CardTitle>
            <CardDescription>请输入您的账号和密码登录系统</CardDescription>
          </CardHeader>
          {error && (
            <div className="px-6 -mt-4">
              <div className="bg-red-50 border border-red-400 text-red-700 px-4 py-3 rounded relative" role="alert">
                <span className="block sm:inline">{error}</span>
              </div>
            </div>
          )}
          <form onSubmit={handleLogin}>
            <CardContent className="space-y-4">
              <Button
                type="button"
                variant="outline"
                className="w-full border-green-600 text-green-600 hover:bg-green-50"
                onClick={async () => {
                  setError(null);
                  setIsLoading(true);
                  try {
                    const response = await apiService.auth.guestLogin();
                    if (response.error) {
                      setError(response.error);
                      return;
                    }
                    router.push("/dashboard");
                  } catch (error: unknown) {
                    const errorMessage = error instanceof Error ? error.message : '未知错误';
                    setError(`访客登录失败: ${errorMessage}`);
                  } finally {
                    setIsLoading(false);
                  }
                }}
                disabled={isLoading}
              >
                快速开始 <ArrowRight className="ml-2 h-4 w-4" />
              </Button>
              <div className="relative">
                <div className="absolute inset-0 flex items-center">
                  <span className="w-full border-t" />
                </div>
                <div className="relative flex justify-center text-xs uppercase">
                  <span className="bg-white px-2 text-gray-500">或</span>
                </div>
              </div>
              <div className="space-y-2">
                <Label htmlFor="email">邮箱</Label>
                <Input
                  id="email"
                  type="email"
                  placeholder="请输入邮箱地址"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  required
                  disabled={isLoading}
                />
              </div>
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <Label htmlFor="password">密码</Label>
                  <Link href="/forgot-password" className="text-sm text-green-600 hover:text-green-800">
                    忘记密码?
                  </Link>
                </div>
                <Input
                  id="password"
                  type="password"
                  placeholder="请输入密码"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  required
                  disabled={isLoading}
                />
              </div>
              <div className="flex items-center space-x-2">
                <Checkbox 
                  id="remember" 
                  checked={rememberMe} 
                  onCheckedChange={(checked) => setRememberMe(checked as boolean)}
                  disabled={isLoading}
                />
                <Label htmlFor="remember" className="text-sm">
                  记住我
                </Label>
              </div>
            </CardContent>
            <CardFooter>
              <Button 
                type="submit" 
                className="w-full bg-green-600 hover:bg-green-700"
                disabled={isLoading}
              >
                {isLoading ? '登录中...' : '登录'}
                {!isLoading && <ArrowRight className="ml-2 h-4 w-4" />}
              </Button>
            </CardFooter>
          </form>
        </Card>

        <div className="mt-6 text-center">
          <p className="text-gray-600">
            还没有账号?
            <Link href="/register" className="ml-1 text-green-600 hover:text-green-800">
              注册
            </Link>
          </p>
        </div>
      </div>
    </div>
  )
}
